<template>
  <view class="chat-container" :style="{ paddingBottom: keyboardHeight + 'px' }">
    <!-- Header -->
    <!-- <view class="header">
      <view class="back-icon" @tap="goBack">
        <text class="iconfont icon-webchat"></text>
      </view>
      <text class="title">AI助手</text>
    </view> -->
    
    <!-- Chat Messages -->
    <!-- <scroll-view 
      scroll-y 
      class="message-list"
      :scroll-top="scrollTop"
      :style="{ paddingBottom: inputAreaHeight + 'px' }"
      @scrolltoupper="loadMoreMessages"
    > -->
	<scroll-view
	  scroll-y 
	  class="message-list"
	  :scroll-top="scrollTop"
	  :style="{ paddingBottom: inputAreaHeight + 'px' }"
	>
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        class="message-item"
        :class="msg.type === 'user' ? 'message-user' : 'message-ai'"
      >
        <view class="avatar">
          <image :src="msg.type === 'user' ? userAvatar : aiAvatar"></image>
        </view>
        <view class="message-content">
          <text>{{msg.content}}</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- Input Area -->
    <view 
      class="input-area"
      :style="{ bottom: keyboardHeight + 'px' }"
    >
      <textarea
        v-model="inputMessage"
        class="input"
        :adjust-position="false"
        :show-confirm-bar="false"
        placeholder="请输入问题..."
        :disabled="loading"
        @focus="onInputFocus"
        @blur="onInputBlur"
        @linechange="onLineChange"
        @confirm="sendMessage"
        auto-height
      />
      <view 
        class="send-btn"
        :class="{disabled: loading || !inputMessage.trim()}"
        @tap="sendMessage"
      >
        发送
      </view>
    </view>
  </view>
</template>

<script>
	import {getChat,getChatStream} from "@/api/chat.js"
	import userAvatar from '@/static/img/user-avatar.png'
	import aiAvatar from '@/static/img/ai-avatar.png'
	import config from '@/config'
export default {
  data() {
    return {
      messages: [],
	  res_msg:null,
      inputMessage: '',
      loading: false,
      scrollTop: 0,
      userAvatar: userAvatar,
      aiAvatar: aiAvatar,
      page: 1,
      pageSize: 20,
      keyboardHeight: 0,
      inputAreaHeight: 110, // 输入区域基础高度，单位rpx
      textareaHeight: 0
    }
  },
  
  onLoad() {
    // this.initChat()
    // 监听键盘高度变化
    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = res.height
      if (res.height > 0) {
        this.scrollToBottom()
      }
    })
  },
  
  onUnload() {
    // 移除键盘监听
    uni.offKeyboardHeightChange()
  },
  
  methods: {
    // 输入框获得焦点
    onInputFocus() {
      // 延迟滚动，确保键盘弹出后再滚动
      setTimeout(() => {
        this.scrollToBottom()
      }, 100)
    },
    
    // 输入框失去焦点
    onInputBlur() {
      this.keyboardHeight = 0
    },
    
    // 监听输入框行数变化
    onLineChange(e) {
      // 更新文本框高度
      this.textareaHeight = e.detail.height || 0
      this.scrollToBottom()
    },
    
    // 初始化聊天
    // async initChat() {
    //   try {
    //     // 加载历史消息
    //     const historyMessages = await this.loadChatHistory(1)
    //     this.messages = historyMessages.reverse()
    //     this.scrollToBottom()
    //   } catch (error) {
    //     uni.showToast({
    //       title: '加载聊天记录失败',
    //       icon: 'none'
    //     })
    //   }
    // },
    
    // 加载聊天历史
    // async loadChatHistory(page) {
    //   try {
    //     // 这里替换为实际的API调用
    //     const response = await uni.request({
    //       url: 'your-api-endpoint/chat-history',
    //       data: {
    //         page,
    //         pageSize: this.pageSize
    //       }
    //     })
    //     return response.data
    //   } catch (error) {
    //     throw error
    //   }
    // },
    
    // 发送消息
    sendMessage() {
      if (this.loading || !this.inputMessage.trim()) return
      
      const userMessage = {
        type: 'user',
        content: this.inputMessage.trim(),
        timestamp: Date.now()
      }
      
      this.messages.push(userMessage)
      this.scrollToBottom()
      
      this.loading = true
      this.inputMessage = ''
      
      try {
		  console.log("发送消息：",userMessage.content)
        // 调用AI接口获取回复
        this.getAIResponse(userMessage.content)
		// console.log("回复消息：",this.res_msg)
        
  //       const aiMessage = {
  //         type: 'ai',
  //         content: this.res_msg,
  //         timestamp: Date.now()
  //       }
        
  //       this.messages.push(aiMessage)
        this.scrollToBottom()
        
      } catch (error) {
		  throw error
        uni.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取AI回复
    getAIResponse(message) {
        // 这里替换为实际的非流式AI API调用
        getChat(message).then(res => {
        	if (res.code == 200) {
				const aiMessage = {
				  type: 'ai',
				  content: res.msg,
				  timestamp: Date.now()
				}
				
				this.messages.push(aiMessage)
        	}
        })
		// 这里替换为实际的流式AI API调用
		// getChatStream(message).then(res => {
		// 	// console.log("getChatStream",res.split("data:"))
		// 		let mes = res.split("data:")
		// 		let res_mes = ""
		// 		// 接收数据
		// 		mes.slice(1).forEach(item => {
		// 			const data = JSON.parse(item).result.output.content
		// 			res_mes+=data
		// 		    console.log("res-item",res_mes);
		// 		});
		// 		// res_mes = res_mes.split(0,-2)
		// 		const aiMessage = {
		// 		  type: 'ai',
		// 		  content: res_mes,
		// 		  timestamp: Date.now()
		// 		}
				
		// 		this.messages.push(aiMessage)
		// });
      
    },
    // 加载更多历史消息
    // async loadMoreMessages() {
    //   if (this.loading) return
      
    //   this.loading = true
    //   try {
    //     const moreMessages = await this.loadChatHistory(++this.page)
    //     if (moreMessages.length) {
    //       this.messages.unshift(...moreMessages.reverse())
    //     }
    //   } catch (error) {
    //     uni.showToast({
    //       title: '加载更多消息失败',
    //       icon: 'none'
    //     })
    //   } finally {
    //     this.loading = false
    //   }
    // },
    
    // 滚动到底部
    scrollToBottom() {
      setTimeout(() => {
        this.scrollTop = 9999999
      }, 100)
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
  border-bottom: 1rpx solid #eee;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
  padding: 20rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
}

.message-list {
  flex: 1;
  padding: 108rpx 30rpx 0;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
  padding: 0 50rpx; /* 添加左右内边距 */
}

.message-user {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.message-content {
  max-width: 70%;
  margin: 0 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  word-break: break-all;
}

.message-user .message-content {
  background-color: #007AFF;
  color: #fff;
}

.message-ai {
  flex-direction: row;
  padding: 0 20rpx 30rpx 0;
}
.message-ai .message-content {
  background-color: #fff;
  color: #333;
}

.input-area {
  position: fixed;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: flex-end;
  border-top: 1rpx solid #eee;
  transition: bottom 0.3s;
}

.input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-right: 20rpx;
  max-height: 200rpx;
  font-size: 28rpx;
}

.send-btn {
  width: 120rpx;
  height: 70rpx;
  background-color: #007AFF;
  color: #fff;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.send-btn.disabled {
  background-color: #ccc;
}
</style>